package com.bh.common.utils.weapp;

import cn.hutool.http.*;
import com.alibaba.fastjson2.JSONObject;
import com.bh.common.utils.Base64;
import com.bh.common.utils.http.HttpUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 我们聊天跑龙套
 *
 * @author shuangluxing@163.com
 * @date 2023/05/15
 */
public class WeChatUtil {
    private static final Logger log = LoggerFactory.getLogger(WeChatUtil.class);

    public static JSONObject getOpenid(String code) {
        // 配置请求参数
        Map<String, String> param = new HashMap<>();
        param.put("appid", WeChatConfig.WX_LOGIN_APPID);
        param.put("secret", WeChatConfig.WX_LOGIN_SECRET);
        param.put("grant_type", WeChatConfig.WX_LOGIN_GRANT_TYPE);
        param.put("js_code", code);
        // 发送请求
        String wxResult = HttpUtils.sendGet(WeChatConfig.WX_LOGIN_URL, param);
        log.info(wxResult);

        return JSONObject.parseObject(wxResult);
    }

    public static JSONObject getUserInfo(String encryptedData, String sessionKey, String iv) throws Exception {
        // 被加密的数据
        byte[] dataByte = Base64.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.decode(sessionKey);
        // 偏移量
        byte[] ivByte = Base64.decode(iv);
        try {
            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            // 初始化
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, StandardCharsets.UTF_8);
                return JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String getPhoneNumber(String phoneCode) {
        String result = null;
        try {
            String tokenUrl = WeChatConfig.WX_TOKEN_URL + "&appid={0}&secret={1}";
            String replaceTokenUrl = tokenUrl.replace("{0}", WeChatConfig.WX_LOGIN_APPID).replace("{1}", WeChatConfig.WX_LOGIN_SECRET);
            String res = HttpUtil.get(replaceTokenUrl);
            JSONObject jsonToken = JSONObject.parseObject(res);
            String accessToken = jsonToken.getString("access_token");

            String phoneUrl = WeChatConfig.WX_PHONE_URL + "?access_token={0}";
            String replacePhoneUrl = phoneUrl.replace("{0}", accessToken);
            HashMap<String, Object> requestParam = new HashMap<>();
            // 手机号调用凭证
            requestParam.put("code", phoneCode);
            String jsonStr = JSONObject.toJSONString(requestParam);
            HttpResponse response = HttpRequest.post(replacePhoneUrl)
                    .header(Header.CONTENT_ENCODING, "UTF-8")
                    // 发送json数据需要设置contentType
                    .header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded")
                    .body(jsonStr)
                    .execute();
            if (response.getStatus() == HttpStatus.HTTP_OK) {
                result = response.body();
            }
        } catch (HttpException e) {
            e.printStackTrace();
        }
        Map<String,Object> phoneJson = (Map<String, Object>) JSONObject.parseObject(result).get("phone_info");
        if (phoneJson != null && phoneJson.get("phoneNumber") != null) {
            return phoneJson.get("phoneNumber").toString();
        }
        return null;
    }
}
